#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <dirent.h>


#include "internal.h"
#include "util.h"

void *
pkg_calloc(size_t number, size_t size)
{
        void *rval;
        rval = calloc(number, size);
        if (rval == NULL) {
                PKG_CLIENT_CRASH(__func__, "Allocation failure.");
        }

        return (rval);
}

/* In place trim of trailing newline char. */
void
_pkg_util_trim_newline(char *to_trim)
{
	char *f;
	
	if (to_trim == NULL)
		return;
	f = strrchr(to_trim, (int)'\n');
	if (f != NULL && *(f + 1) == '\0') {
		*f = '\0';
        }
}

/* Null-safe strcmp(). */
int
_nsstrcmp(const void *a, const void *b)
{
	const char *sa;
	const char *sb;

	sa = a;
	sb = b;
	if (sa == NULL && sb != NULL) {
		return (-1);
        } else if (sa != NULL && sb == NULL) {
		return (1);
        } else if (sa == NULL && sb == NULL) {
		return (0);
        }
	return (strcmp(sa, sb));
}

/* String compare for qsort. */
int
_qsstrcmp(const void *a, const void *b)
{
	const char *const *sa;
	const char *const *sb;

	sa = a;
	sb = b;

	return (strcmp(*sa, *sb));
}

void
_pkg_util_path_join(char *final, const char *prefix, const char *file)
{
        strcpy(final, prefix);
        strcat(final, "/");
        strcat(final, file);
}

/* Use feof to check this. */
void
_pkg_util_fp_copy(FILE *dst, FILE *src)
{
        char line[LINE_MAX];
        while (fgets(line, sizeof(line), src) != NULL) {
                if (fputs(line,dst) == EOF) {
                        return;
                }
        }
}
